package com.qiantu.phone.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.base.DensityUtils;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.event.RefreshRecommendSceneSwitchEvent;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.event.SceneChangeEvent;
import com.qiantu.phone.scan.ScanCodeActivity;
import com.qiantu.phone.ui.activity.AddDevice1Activity;
import com.qiantu.phone.ui.activity.EditLinkageActivity;
import com.qiantu.phone.ui.activity.EditLinkageActivityNew;
import com.qiantu.phone.ui.activity.EditSceneActivityNew;
import com.qiantu.phone.ui.activity.SceneAddGuideActivity;
import com.qiantu.phone.ui.activity.SceneManageActivity;
import com.qiantu.phone.ui.activity.SceneOrderActivity;
import com.qiantu.phone.ui.activity.AddConditionActivity;
import com.qiantu.phone.ui.dialog.AreaSelectDialog;
import com.qiantu.phone.ui.dialog.OptionDialog;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.SPUtils;
import com.qiantu.phone.widget.ViewPagerIndicator;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SmartFragment extends TitleBarFragment<AppActivity> {
    private String[] tabs;
    private ViewPagerIndicator tabBar;
    private View btnAdd;
    private View btnEdit;
    private TextView timelineTV;
    private FrameLayout selectAreaLayout;
    private ViewPager viewPager;
    private int currentItem;

    private TextView selectArea;

    public SmartFragment() {
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if(savedInstanceState != null){
            currentItem = savedInstanceState.getInt("currentItem", 0);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_smart;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        selectArea = findViewById(R.id.select_area);
        tabBar = findViewById(R.id.tab_bar);
        btnAdd = findViewById(R.id.btn_add);
        btnEdit = findViewById(R.id.btn_edit);
        timelineTV = findViewById(R.id.tv_timeline);
        selectAreaLayout = findViewById(R.id.layout_select_area);
        viewPager = findViewById(R.id.view_pager);

        selectArea.setText(getString(R.string.unlimited_area) );
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        selectAreaLayout.setVisibility(View.VISIBLE);
                        timelineTV.setVisibility(View.GONE);
                        btnEdit.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        selectAreaLayout.setVisibility(View.GONE);
                        timelineTV.setVisibility(View.VISIBLE);
                        btnEdit.setVisibility(View.GONE);
                        break;
                    default:
                        selectAreaLayout.setVisibility(View.VISIBLE);
                        timelineTV.setVisibility(View.GONE);
                        btnEdit.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        setOnClickListener(btnAdd, btnEdit,selectArea);
        initViewPager();
    }

    SceneListFragment sceneFragment;
    LinkageFragment linkageFragment;
    TimeFragmentNew timeFragmentNew;
    private void initViewPager() {
        FragmentPagerAdapter<Fragment> mPagerAdapter = new FragmentPagerAdapter<>(this);
//        switchSceneRecommend = SPUtils.getInstance().getBoolean("switchSceneRecommend", true);
//        if(switchSceneRecommend){
//            tabs = new String[]{getString(R.string.recommend), getString(R.string.scene), getString(R.string.linkage), getString(R.string.time)};
//            mPagerAdapter.addFragment(new RecommendSceneFragment());
//        }else{
//            tabs = new String[]{getString(R.string.scene), getString(R.string.linkage)};
//        }
        tabs = new String[]{getString(R.string.linkage)};
        sceneFragment = SceneListFragment.newInstance(0);
        linkageFragment = new LinkageFragment();
//        mPagerAdapter.addFragment(sceneFragment);
        mPagerAdapter.addFragment(linkageFragment);
        viewPager.setAdapter(mPagerAdapter);
        tabBar.setupViewpager(viewPager);
        tabBar.setCurrentItem(currentItem);
        tabBar.setTitles(tabs);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if(viewPager != null){
            outState.putInt("currentItem", viewPager.getCurrentItem());
        }
    }

    @Override
    protected void initData() {

    }

    public ViewPager getViewPager() {
        return viewPager;
    }

    @Override
    public void onClick(View view) {
        if (view == btnAdd){
            showAddDialog(view);
        }else if (view == btnEdit){
            showOptionDialog(view);
        }else if (view == selectArea) {
            showSelectAreaDialog(selectArea);
        }
    }

    private OptionDialog addDialog;

    private void showAddDialog(View atView) {
        if (addDialog == null) {
            List<OptionDialog.Option> options = new ArrayList<>();
//            options.add(new OptionDialog.Option(R.attr.icon_home_addscenes, "添加场景"));
            options.add(new OptionDialog.Option(R.attr.icon_home_addlinkage, "添加联动"));
            addDialog = new OptionDialog(getContext())
                    .setOptions(options).setListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                            addDialog.dismiss();
                            Intent intent = null;
                            OptionDialog.Option option = options.get(position);
                            switch (option.title) {
                                case "添加场景":
                                    startActivity(SceneAddGuideActivity.class);
                                    break;
                                case "添加联动":
//                                    List<ControllerBean> beans = LLControllerDBManager.getInstance(getContext()).getControllersByProductModel("0x1501");
//                                    if(beans.size() == 0 || LLSceneLinkageUtil.compareVersion("1.4.0", beans.get(0).getVersion())){
//                                        startActivity(EditLinkageActivityNew.class);
//                                    }else{
                                        startActivity(EditLinkageActivity.class);
//                                    }
                                    break;
                            }
                        }
                    });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(getResources().getDimensionPixelSize(R.dimen.dp_10))
                    .asCustom(addDialog);
        }
        addDialog.show();
    }

    private OptionDialog optionDialog;
    private void showOptionDialog(View atView) {
        if (optionDialog == null) {
            List<OptionDialog.Option> options = new ArrayList<>();
            options.add(new OptionDialog.Option(R.attr.icon_navigationbar_edit_black, getString(R.string.scene_operation)));
            options.add(new OptionDialog.Option(R.attr.icon_intelligent_sort, getString(R.string.scene_order)));
            optionDialog = new OptionDialog(getContext())
                    .setOptions(options).setListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                            if (position == 0){
                                startActivity(SceneManageActivity.class);
                            }else if (position == 1){
                                startActivity(SceneOrderActivity.class);
                            }
                            optionDialog.dismiss();
                        }
                    });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(DensityUtils.dip2px(getContext(), 16))
                    .asCustom(optionDialog);
        }
        optionDialog.show();
    }

    AreaSelectDialog selectDialog;
    private void showSelectAreaDialog(View atView) {
        if (selectDialog == null) {
            selectDialog = new AreaSelectDialog(getContext(), AreaSelectDialog.TYPE_SMART) {
                @Override
                public void onSmartSave(List<SceneBean> sceneBeans, boolean allSelect, boolean commonSelect, Map<String, RoomBean> selectAreas) {
                    sceneFragment.setTotalData(sceneBeans);
                    linkageFragment.setSerchKey(allSelect,commonSelect,selectAreas);
                    selectArea.setText(selectDialog.getTitle());
                }
            };
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(DensityUtils.dip2px(getContext(), 0))
                    .offsetY(-DensityUtils.dip2px(getContext(), 50))
                    .asCustom(selectDialog);
        }
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        floors.remove(0);
        selectDialog.setFloorBeans(floors);
        selectDialog.show();
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshSceneEvent(RefreshSceneEvent event) {
        List<SceneBean> scenes;
        if(selectDialog == null){
            scenes = LLSceneDBManager.getInstance(getContext()).getAll();
        }else{
            scenes = selectDialog.getAllSceneFormSelectArea();
        }
        sceneFragment.setTotalData(scenes);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSceneChangeEvent(SceneChangeEvent event) {
        SceneBean sceneBean = LLSceneDBManager.getInstance(getContext()).getSceneBySerialNo(event.sceneSerialNo);
        sceneFragment.updateSceneData(sceneBean);

    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!isHidden()){
            getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!isHidden()){
            getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
        }
    }
}